package com.app.reportproblem;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.reportproblem.MyUI.MyClickAbleImageView;
import com.app.reportproblem.Utils.PreferenceHelper;
import com.app.reportproblem.bean.ObjProblem;
import com.app.reportproblem.httpclient.HttpClientHelper;
import com.app.reportproblem.httpclient.MyJsonHttpResponseHandler;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

public class ViewProblemTestActivity extends Activity implements
		LocationListener, OnClickListener {
	TextView btnBack;
	private GoogleMap googleMap;
	private ArrayList<ObjProblem> mMyMarkersArray;
	private HashMap<Marker, ObjProblem> mMarkersHashMap;

	int categoryId;
	String title;
	TextView txtCountProblem;
	PreferenceHelper preferenceHelper;

	double mLatitude;
	double mLongitude;
	DisplayImageOptions options = new DisplayImageOptions.Builder()
			.cacheInMemory(false).cacheOnDisc(true)
			.bitmapConfig(Config.RGB_565).build();

	Handler mHandler = new Handler();

	ImageView icFixed;
	int reportId = 0;
	int fixed = 0;
	
	Dialog dF;
	MyClickAbleImageView btnMylocation;
	Location location;
	
	static HashMap<String,String> loadImagesFlag = new HashMap<String, String>();
	private Marker mSelectedMarker;
    private boolean mRefreshingInfoWindow;
    
    ImageView actionbar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_problem_test);

		preferenceHelper = new PreferenceHelper(this);
		categoryId = getIntent().getIntExtra("categoryId", 0);
		title = getIntent().getStringExtra("title");

		fixed = preferenceHelper.getUserFixed();
		actionbar = (ImageView) findViewById(R.id.actionbar);
		ImageLoader.getInstance().displayImage(preferenceHelper.getUrlActionBar(), actionbar, options);
		btnBack = (TextView) findViewById(R.id.btn_back);
		txtCountProblem = (TextView) findViewById(R.id.txt_count_problem);
		
		btnMylocation = (MyClickAbleImageView) findViewById(R.id.my_location);

		mLatitude = getIntent().getDoubleExtra("lat", 0);
		mLongitude = getIntent().getDoubleExtra("lon", 0);
		icFixed = (ImageView) findViewById(R.id.ic_fixed);

		// Initialize the HashMap for Markers and MyMarker object
		mMarkersHashMap = new HashMap<Marker, ObjProblem>();
		/*
		 * mMyMarkersArray.add(new ObjProblem(20.9593294, 105.7965923,
		 * "hiiii\n",
		 * "http://fl.jshort.vn/upload/2014/04/20/5353e14a97142_thumbnail.jpg"
		 * ,"","Thientvse001")); mMyMarkersArray.add(new ObjProblem(20.9593278,
		 * 105.7965938, "Khong co chi",
		 * "http://fl.jshort.vn/upload/2014/04/23/5357caf6c5c9a_thumbnail.jpg"
		 * ,"","Thientvse002")); mMyMarkersArray.add(new ObjProblem(20.9593,
		 * 105.797, "Ho ho",
		 * "http://fl.jshort.vn/upload/2014/04/24/53593cf477274_thumbnail.jpg"
		 * ,"","Thientvse003")); mMyMarkersArray.add(new ObjProblem(20.9594,
		 * 105.797, "Ho ho",
		 * "http://fl.jshort.vn/upload/2014/04/24/535921bae1c1b_thumbnail.jpg"
		 * ,"","Thientvse004"));
		 */

		setUpMap();
		getProblem();
		init();

	}

	void init() {
		btnBack.setOnClickListener(this);
		icFixed.setOnClickListener(this);
		btnMylocation.setOnClickListener(this);
	}
	
	//create a AsyncTask for load image asynchronously 

	public class FetchImageTask extends AsyncTask<String, Integer, Bitmap> 
	{

	        @Override
	        protected Bitmap doInBackground(String... arg0) {
	            Bitmap b = null;
	            try {
	                Thread.sleep(500);
	                b = BitmapFactory.decodeStream((InputStream) new URL(arg0[0]).getContent());
	            } catch (MalformedURLException e) {
	                //e.printStackTrace();
	            } catch (IOException e) {
	                //e.printStackTrace();
	            }catch (Exception e){
	                e.printStackTrace();
	            }
	            return b;
	        }
	}
	

	@SuppressLint("NewApi")
	private void setUpMap() {
		// Do a null check to confirm that we have not already instantiated the
		// map.
		if (googleMap == null) {
			// Try to obtain the map from the SupportMapFragment.
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.map)).getMap();

			// Check if we were successful in obtaining the map.

			if (googleMap != null) {
				googleMap
						.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
							@Override
							public boolean onMarkerClick(
									com.google.android.gms.maps.model.Marker marker) {
								marker.showInfoWindow();
								if (fixed == 1) {
									icFixed.setVisibility(View.VISIBLE);
								} else {

								}
								LatLng latLng = new LatLng(marker.getPosition().latitude, marker.getPosition().longitude);
								googleMap.moveCamera(CameraUpdateFactory
										.newLatLng(latLng));
								googleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
								return true;
							}
						});
			} else
				Toast.makeText(getApplicationContext(),
						"Unable to create Maps", Toast.LENGTH_SHORT).show();
		}

		googleMap.setOnMapClickListener(new OnMapClickListener() {

			@Override
			public void onMapClick(LatLng point) {
				icFixed.setVisibility(View.GONE);
			}
		});

		// Enabling MyLocation in Google Map
		googleMap.setMyLocationEnabled(true);
		googleMap.getUiSettings().setMyLocationButtonEnabled(false);
		
		/*  // Creating an instance of MarkerOptions
        MarkerOptions markerOptions = new MarkerOptions();

        // Setting position for the marker
        markerOptions.position(new LatLng(mLatitude, mLongitude));

        // Setting custom icon for the marker
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_location));

        // Adding the marker to the map
        googleMap.addMarker(markerOptions);
        
        googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
			
			@Override
			public boolean onMarkerClick(Marker marker) {
				return false;
			}
		});
*/
		// Getting LocationManager object from System Service
		// LOCATION_SERVICE
		LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		// Creating a criteria object to retrieve provider
		Criteria criteria = new Criteria();

		// Getting the name of the best provider
		String provider = locationManager.getBestProvider(criteria, true);

		// Getting Current Location From GPS
		location = locationManager.getLastKnownLocation(provider);

		if (location != null) {
			onLocationChanged(location);
		}

		locationManager.requestLocationUpdates(provider, 20000, 0,
				new android.location.LocationListener() {

					@Override
					public void onStatusChanged(String provider, int status,
							Bundle extras) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onProviderEnabled(String provider) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onProviderDisabled(String provider) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onLocationChanged(Location location) {
						// TODO Auto-generated method stub
						mLatitude = (float) location.getLatitude();
						mLongitude = (float) location.getLongitude();
						LatLng latLng = new LatLng(mLatitude, mLongitude);

						Log.i("DATA", "LAT: " + mLatitude + "LONG: "
								+ mLongitude);

						googleMap.moveCamera(CameraUpdateFactory
								.newLatLng(latLng));
						googleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
					}
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
		setUpMap();
	}

	// getProblem
	public void getProblem() {
		Log.i("DATA", "LAY DC van de 1");
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						Log.i("DATA", "LAY DC van de 2");
						super.onFailure(error);
					}

					@Override
					public void onSuccess(JSONObject re) {
						try {
							Log.i("DATA", "LAY DC van de 3");
							int status = re.getInt("status");
							if (status == 200) {
								Log.i("DATA", "LAY DC van de 4");
								JSONArray data = re.getJSONArray("data");
								mMyMarkersArray = new ArrayList<ObjProblem>();
								Log.i("DATA", "PROBLEM: " + data.toString());
								
								txtCountProblem.setText(title+"("+data.length()+")");
								
								for (int i = 0; i < data.length(); i++) {
									JSONObject jo = data.getJSONObject(i);

									ObjProblem objProblem = new ObjProblem();

									int reportId = jo.getInt("reportId");
									double lat = jo.getDouble("lat");
									double lon = jo.getDouble("lon");
									String note = jo.getString("note");
									String address = jo.getString("address");
									String image = jo
											.getString("thumbnail_image");

									// set vao obj
									objProblem.setReportId(reportId);
									objProblem.setLat(lat);
									objProblem.setLon(lon);
									objProblem.setAddress(address);
									objProblem.setImage(image);
									objProblem.setNote(note);
									mMyMarkersArray.add(objProblem);
								}
								plotMarkers(mMyMarkersArray);
							} else {
								Log.i("DATA", "LAY DC van de 5");
							}

						} catch (JSONException e) {
							Log.i("DATA", "LAY DC van de 6");
							e.printStackTrace();
						}
					}

				});

		httpClientHelper.getProblem(categoryId, (float) mLongitude,
				(float) mLatitude);
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		mLatitude = (float) location.getLatitude();
		mLongitude = (float) location.getLongitude();
		LatLng latLng = new LatLng(mLatitude, mLongitude);

		Log.i("DATA", "LAT: " + mLatitude + "LONG: " + mLongitude);

		googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
		googleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
	}

	private void plotMarkers(ArrayList<ObjProblem> markers) {
		if (markers.size() > 0) {
			for (ObjProblem objProblem : markers) {

				// Create user marker with custom icon and other options
				MarkerOptions markerOption = new MarkerOptions()
						.position(new LatLng(objProblem.getLat(), objProblem
								.getLon()));
				markerOption.icon(BitmapDescriptorFactory
						.fromResource(R.drawable.problem));

				Marker currentMarker = googleMap.addMarker(markerOption);
				mMarkersHashMap.put(currentMarker, objProblem);
				
				if (objProblem.getLat() == mLatitude) {
					
				} else {
					googleMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
				}
			}
		}
	}

	public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
		public MarkerInfoWindowAdapter() {
		}

		@Override
		public View getInfoWindow(final Marker marker) {
			return null;
		}

		View v;
		@Override
		public View getInfoContents(final Marker marker) {
			if (!mRefreshingInfoWindow) {
                mSelectedMarker = marker;
                v = getLayoutInflater().inflate(R.layout.maker_info, null, false);
				final ObjProblem objProblem = mMarkersHashMap.get(marker);
	
				TextView nameProblem = (TextView) v.findViewById(R.id.txt_name_problem);
				TextView nameRepoter = (TextView) v.findViewById(R.id.txt_name_reporter);
				TextView locationProblem = (TextView) v.findViewById(R.id.txt_location);
				final ImageView image = (ImageView) v.findViewById(R.id.img_problem);
				String urlTest = "http://fl.jshort.vn/upload/2014/04/29/535f1a934ba68_thumbnail.jpg";
				ImageLoader.getInstance().displayImage(objProblem.getImage(),
						image, options, new SimpleImageLoadingListener() {
	
							@Override
							public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
								super.onLoadingComplete(imageUri, view, loadedImage);
								Log.i("DATA", "---------------");
								//getInfoContents(marker);
								refreshInfoWindow();
							}
						});
				TextView note = (TextView) v.findViewById(R.id.txt_note);
				
				
				
				reportId = objProblem.getReportId();
				nameProblem.setText(title);
				// nameRepoter.setText("Reporter: "+objProblem.getUserName());
				locationProblem.setText("Location: Latitude: "
						+ objProblem.getLat() + "-" + "Longitude: "
						+ objProblem.getLon());
				Log.i("DATA", "Link :" + objProblem.getImage());
				// Picasso.with(ViewProblemTestActivity.this).load(objProblem.getImage()).into(image);
	
				note.setText("Note: " + objProblem.getNote());
           	}
			return v;
		}

	}
	
	 private void refreshInfoWindow() {
        if (mSelectedMarker == null) {
            return;
        }
        mRefreshingInfoWindow = true;
        mSelectedMarker.showInfoWindow();
        mRefreshingInfoWindow = false;
    }
	      

	private int manageMarkerIcon(String markerIcon) {
		if (markerIcon.equals("icon1"))
			return R.drawable.icon1;
		else if (markerIcon.equals("icon2"))
			return R.drawable.icon2;
		else if (markerIcon.equals("icon3"))
			return R.drawable.icon3;
		else if (markerIcon.equals("icon4"))
			return R.drawable.icon4;
		else if (markerIcon.equals("icon5"))
			return R.drawable.icon5;
		else if (markerIcon.equals("icon6"))
			return R.drawable.icon6;
		else if (markerIcon.equals("icon7"))
			return R.drawable.icon7;
		return R.drawable.icon1;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			closeActivityAnim();
			break;
		case R.id.ic_fixed:
			showDialogCoonfirmFixed();
			break;
			
		case R.id.my_location:
			   googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new    
					   LatLng(location.getLatitude(),     
					   location.getLongitude()), 12));
			break;
		default:
			break;
		}

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		closeActivityAnim();
	}

	public void closeActivityAnim() {
		finish();
		overridePendingTransition(R.anim.open_main, R.anim.close_next);
	}

	void fixProblem() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
					}

					@Override
					public void onSuccess(JSONObject re) {
						try {
							int status = re.getInt("status");
							switch (status) {
							case 200:
								googleMap.clear();
								getProblem();
								icFixed.setVisibility(View.GONE);
								Toast.makeText(ViewProblemTestActivity.this,
										"Fixed Success.", Toast.LENGTH_SHORT)
										.show();
								break;

							case 400:
								Toast.makeText(ViewProblemTestActivity.this,
										"Fixed Failure.", Toast.LENGTH_SHORT)
										.show();
								break;
							case 404:
								Toast.makeText(ViewProblemTestActivity.this,
										"Fixed Failure.", Toast.LENGTH_SHORT)
										.show();
								break;
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

				});
		httpClientHelper.fixProblem(preferenceHelper.getUserId(), reportId);
	}

	void showDialogCoonfirmFixed() {
		dF = new Dialog(ViewProblemTestActivity.this);
		dF.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dF.setContentView(R.layout.dialog_confirm_fix);

		Button btnOk = (Button) dF.findViewById(R.id.btnOk);
		Button btnCancel = (Button) dF.findViewById(R.id.btnCancel);
		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dF.dismiss();
				fixProblem();
			}
		});

		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dF.dismiss();
			}
		});
		dF.show();
	}

}
